package com.huawei.petapp2.cart;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.petapp2.MyDialog;
import com.huawei.petapp2.R;
import com.huawei.petapp2.call.ShoppingcartCallback;
import com.huawei.petapp2.constant.HttpUrl;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.entity.Shoppingcart;
import com.huawei.petapp2.fragment.BaseFragment;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CartFragment extends BaseFragment {

    private ListView cart_list;
    private TextView cart_money, cart_check_all, cart_del, cart_buy,cart_num;
    private CartDBOpenHelper dbOpenHelper;
    private boolean flag = true;
    private Context mContext;

    final private static Gson gson=new GsonBuilder().serializeNulls().create();

    private List<Shoppingcart> shoppingcart;
    private View mView;

    @Override
    public void initView(View mView) {
       ;
        this.mContext=mView.getContext();
        this.mView=mView;
        cart_list = this.mView.findViewById(R.id.cart_list);
        cart_money = this.mView.findViewById(R.id.cart_money);
        cart_check_all = this.mView.findViewById(R.id.cart_check_all);
        cart_del = this.mView.findViewById(R.id.cart_del);
        cart_buy = this.mView.findViewById(R.id.cart_buy);
        cart_num= this.mView.findViewById(R.id.cart_num);
       this.shoppingcart=getShoppingcart(this.mView);
        System.out.println("获取的购物车数据"+shoppingcart);
      //  initData();
        initListener();
        cart_money.performClick();

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_cart2;
    }


    public View initView() {
        View view = View.inflate(mContext, R.layout.fragment_cart2, null);
        cart_list = view.findViewById(R.id.cart_list);
        cart_money = view.findViewById(R.id.cart_money);
        cart_check_all = view.findViewById(R.id.cart_check_all);
        cart_del = view.findViewById(R.id.cart_del);
        cart_buy = view.findViewById(R.id.cart_buy);
        cart_num=this.mView.findViewById(R.id.cart_num);
        initListener();
        cart_money.performClick();
        return view;
    }


    public void initData(){
        int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(mContext));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
        


        /*OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/shopcart/list/"+userid)
                .addHeader("Token",token)
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    System.out.println("新的获取购物车数据OnintView"+result);
                    shoppingcart= DateUtil.getList10(result);
                    cart_list.setAdapter(new CartListAdapter(mContext,shoppingcart));
                    System.out.println("新的获取购物车数据请求"+result);
                }
            }
        });*/


       // List<Shoppingcart> cartGoods = getShoppingcart(this.mView);
//        cartGoods.add(new CartGoods(R.drawable.ipad,"IPad 2018","金色 128G",2399.00,1));
//        cartGoods.add(new CartGoods(R.drawable.bamai8,"宝马 i8","白蓝 2015",1999999.00,1));
//        cartGoods.add(new CartGoods(R.drawable.anmuxi,"伊利 安慕希","高端畅饮型 10瓶",69.00,3));
//        cartGoods.add(new CartGoods(R.drawable.xiaomi10,"小米 10","天之蓝 8+256",3999.00,2));
//        cartGoods.add(new CartGoods(R.drawable.huaweip40,"华为 P40 5G","白色 12+512",5999.00,5));


       // super.initData();
    }


    //查询数据库中所有商品
    public List<Shoppingcart> getShoppingcart(View view)
    {
        int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(mContext));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
        List<Shoppingcart> shoppingcarts = null;
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", "zhy");
        String url = HttpUrl.getBaseUrl()+"/shopcart/list/"+userid;
        OkHttpUtils//
                .get()//
                .url(url)//
//                .params(params)//
                .addHeader("Token",token)
                .build()//
                .execute(new ShoppingcartCallback()//
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {

                    }

                    @Override
                    public void onResponse(List<Shoppingcart> response, int id)
                    {
                        shoppingcart=response;
                        cart_list.setAdapter(new CartListAdapter(mContext,shoppingcart));
                        System.out.println("相应的数据"+response);
                    }
                });
        return shoppingcart;

    }




    private void initListener(){
        int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(mContext));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
        //全选单击事件
        cart_check_all.setOnClickListener(v -> {
            if (flag){
                OkHttpClient client = new OkHttpClient();
                Request request1 = new Request.Builder()//获取改用户全部地址
                        .url(HttpUrl.getBaseUrl()+"/shopcart/updateAllSelect/"+userid+"/"+1)
                        .addHeader("Token",token)
                        .build();

                client.newCall(request1).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Looper.prepare();//增加部分
                        if(response.code() >= 200 && response.code() < 300) {
                            String results = response.body().string();
                            System.out.println("新的获取订单请求请求"+results);
                        }
                        Looper.loop();//增加部分
                    }
                });
                flag = false;
            }else {
                OkHttpClient client = new OkHttpClient();
                Request request1 = new Request.Builder()//获取改用户全部地址
                        .url(HttpUrl.getBaseUrl()+"/shopcart/updateAllSelect/"+userid+"/"+0)
                        .addHeader("Token",token)
                        .build();

                client.newCall(request1).enqueue(new Callback() {

                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Looper.prepare();//增加部分
                        if(response.code() >= 200 && response.code() < 300) {
                            String results = response.body().string();
                            System.out.println("新的获取订单请求请求"+results);
                        }
                        Looper.loop();//增加部分
                    }
                });
                flag = true;
            }
            initData();
            Toast.makeText(mContext, "全选！！！", Toast.LENGTH_SHORT).show();
        });

        //合计单击事件
        cart_money.setOnClickListener(v -> {
            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()//获取改用户全部地址
                    .url(HttpUrl.getBaseUrl()+"/shopcart/list/"+userid)
                    .addHeader("Token",token)
                    .build();

            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Looper.prepare();//增加部分
                    double money = 0.0;
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的获取订单请求请求OnintView"+result);
                        shoppingcart= DateUtil.getList10(result);
                        System.out.println("新的获取订单请求请求"+result);
                        for (Shoppingcart g : shoppingcart){
                            if (g.getIsselect()==1){
                                money += Integer.valueOf(g.getCartNum()) * g.getSellPrice();
                            }
                        }
                       // cart_money.setText("合计:￥" + money);
                    }
                    Looper.loop();//增加部分
                }

            });
           // List<Shoppingcart> goods = getShoppingcart(this.mView);

        });

        //删除单击事件
        cart_del.setOnClickListener(v -> {
            MyDialog myDialog = new MyDialog(mContext, R.style.MyDialog);
            myDialog.setTitle("提示")
                    .setMessage("确认删除该订单吗？")
                    .setCancel("取消", dialog -> dialog.dismiss() )
                    .setConfirm("确认", dialog -> {
                        List<Shoppingcart> goods = getShoppingcart(this.mView);
                        for (Shoppingcart g : goods){
                            if (g.getIsselect()==1){
                                delCartGoods(g.getCartId());
                            }
                        }
                        initData();
                        Toast.makeText(mContext, "删除成功", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    })
                    .show();
        });

        //去结算单击事件
        cart_buy.setOnClickListener(v -> {
            PreferenceHelper preferenceHelper = new PreferenceHelper();
            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()//获取改用户全部地址
                    .url(HttpUrl.getBaseUrl()+"/shopcart/list/"+userid)
                    .addHeader("Token",token)
                    .build();

            client.newCall(request1).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Looper.prepare();//增加部分
                    double money = 0.0;
                    boolean isEmp = false;
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的获取订单请求请求OnintView"+result);
                        shoppingcart= DateUtil.getList10(result);
                        System.out.println("新的获取订单请求请求"+result);
                        int i=shoppingcart.get(0).getCartId();
                        preferenceHelper.saveCartid(getContext(),i);
                        for (Shoppingcart g : shoppingcart){
                            if (g.getIsselect()==1){
                                isEmp = true;
                            }
                        }
                        if (!isEmp){
                            Toast.makeText(mContext, "您没有选中任何商品哦~", Toast.LENGTH_SHORT).show();
                        }else {
                            for (Shoppingcart g : shoppingcart){
                                if (g.getIsselect()==1){
                                    money += g.getSellPrice() * Integer.valueOf(g.getCartNum());
                                }
                            }
                            Intent intent = new Intent();
                            intent.putExtra("state","list");
                            intent.putExtra("money",money);
                            intent.setClass(mContext,DingdanActivity.class);
                            startActivity(intent);
                        }
                        Looper.loop();//增加部分
                    }
                }
            });


           // List<Shoppingcart> goods = getShoppingcart(this.mView);

            /**
             * R.anim.slide_in_right:新的Activity进入时的动画，这里是指OtherActivity进入时的动画
             * R.anim.slide_out_left：旧的Activity出去时的动画，这里是指this进入时的动画
             */
            //getActivity().overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            //getActivity().overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
            //getActivity().finish();
        });
    }

    //删除购物车中指定商品
    private void delCartGoods(int g_id){
        dbOpenHelper = new CartDBOpenHelper(mContext, 1);
        //参数依次是表名，以及where条件与约束
        dbOpenHelper.getWritableDatabase().delete(
                "cart",
                "g_id=?",
                new String[]{String.valueOf(g_id)});
        dbOpenHelper.close();
    }

    //查询数据库中所有商品
    /*private List<Shoppingcart> listAllCartGoods() {
        dbOpenHelper = new CartDBOpenHelper(mContext,1);
        Cursor cursor = dbOpenHelper.getReadableDatabase().query(
                "cart",null,null,null,null,null,null
        );
        ArrayList<CartGoods> cartGoods = new ArrayList<>();
        //cart(cart_id,g_id,g_photo,g_name,g_type,g_price,g_num)
        while (cursor.moveToNext()){
            int g_id = Integer.parseInt(cursor.getString(1));
            int g_photo = Integer.parseInt(cursor.getString(2));
            String g_name = cursor.getString(3);
            String g_type = cursor.getString(4);
            double g_price = Double.parseDouble(cursor.getString(5));
            int c_num = Integer.parseInt(cursor.getString(6));
            String c_check = cursor.getString(7);
            cartGoods.add(new CartGoods(g_id,g_photo,g_name,g_type,g_price,c_num,c_check));
        }
        cursor.close();
        dbOpenHelper.close();
        return cartGoods;
    }*/


}
